package com.grad.webstudy.controller;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.github.pagehelper.PageInfo;
import com.grad.webstudy.annota.ApiAuthorization;
import com.grad.webstudy.annota.LoginAuthorization;
import com.grad.webstudy.constants.AuthConstants;
import com.grad.webstudy.constants.FileContants;
import com.grad.webstudy.constants.TokenConstants;
import com.grad.webstudy.constants.UserContants;
import com.grad.webstudy.context.UserContext;
import com.grad.webstudy.dto.ResetPasswordDto;
import com.grad.webstudy.enums.AliyunSmsTemplateCode;
import com.grad.webstudy.exceptions.AliyunException;
import com.grad.webstudy.model.Token;
import com.grad.webstudy.model.User;
import com.grad.webstudy.service.RedisService;
import com.grad.webstudy.service.TokenService;
import com.grad.webstudy.service.UserService;
import com.grad.webstudy.utils.CodeUtils;
import com.grad.webstudy.utils.DateUtils;
import com.grad.webstudy.utils.FileUtils;
import com.grad.webstudy.vo.UserForVue;
import com.grad.webstudy.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @Description: 用户控制层
 * @Author: zjf
 * @Date: 2020/1/14 11:22.
 */
@RestController
@RequestMapping("/user")
@Validated //启用验证
public class UserController {

    public static String code = CodeUtils.getMoreRandomCode();

    public static final String userFile = "/user/";//文件储存位置


    @Autowired
    private UserService userService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private RedisTemplate redisTemplate;


    @ApiAuthorization(auth = AuthConstants.USER_MANAGER_QUERY)
    @GetMapping("/queryAllUsers")
    public PageInfo findUsers(@RequestParam(required = false, defaultValue = "1") int currPage,
                              @RequestParam(required = false, defaultValue = "10") int pageSize,
                              String keyword) {
        return userService.queryAllUsers(currPage, pageSize, keyword);
    }


    @PostMapping("/login")
    public User login(String phone, String password, String validCode,
                      HttpServletResponse response, HttpServletRequest request) {
        //todo 验证码待删除，方便测试才加的
        code = "1111";
        User user = userService.login(phone, password, validCode, code);
        Token token = tokenService.createToken(user);
        response.setHeader(TokenConstants.TOKEN, token.getToken());
        System.out.println(token.getToken());
        user.setRoleIds(token.getToken());
        return user;
    }


    @PostMapping("/loginForAdmin")
    public String loginForAdmin(String username, String password){
        User user=userService.loginForAdmin(username, password);
        Token token=tokenService.createToken(user);
        return token.getToken();
    }

    @GetMapping("/getUserInfo")
    public UserForVue getUserInfo(String token){
        Token token1=tokenService.getToken(token);

        UserForVue result=new UserForVue();

        result.setUsername(token1.getUser().getUsername());
        result.setImagePath(token1.getUser().getImagePath());

        result.setRoles(Collections.singletonList("admin"));
        return result;
    }

    @LoginAuthorization
    @GetMapping("/loginOut")
    public String loginOut(HttpServletRequest request) {
        String token = request.getHeader(TokenConstants.TOKEN);
        tokenService.deleteToken(token);
        return "退出成功";
    }


    @GetMapping("/checkPhone")
    public boolean checkPhone(String phone) {
        return userService.checkPhone(phone);
    }


    @PostMapping("/register")
    public int register(String phone, String password, String validCode) {

        return userService.register(phone, password, validCode, String.valueOf(redisTemplate.opsForValue().get(phone)));
    }

    @ApiAuthorization(auth = AuthConstants.USER_MANAGER)
    @PostMapping("/addUser")
    public int addUser(String username,String password,String phone){
        return userService.addUser(username, password, phone);
    }

    /**
     * 重置密码
     *
     * @param resetPasswordDto
     * @return
     */
    @PutMapping("/resetPassword")
    @LoginAuthorization
    public boolean resetPassword(ResetPasswordDto resetPasswordDto) {
        return userService.resetPassword(resetPasswordDto, String.valueOf(redisTemplate.opsForValue().get(resetPasswordDto.getPhone())));
    }

    /**
     * 校验验证码是否正确
     *
     * @param validCode
     * @return
     */
    @GetMapping("/checkCode")
    private boolean checkCode(String validCode) {
        return Objects.equals(validCode, code);
    }


    /**
     * 调用阿里云服务发送短信验证码
     *
     * @param phone
     */
    @GetMapping("/getCode")
    public String getAliyunCode(String phone, @Max(3) @Min(1) @RequestParam(required = true) int templateType) {

        code = CodeUtils.getRandomCode();
        System.out.println("验证码：" + code);
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "8888L888TA88I4FoFcpMriNeFGRvckA9E", "I6OftsuFvhjVuZTU8Xj64bdJqEJIGkllllll");
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", "在线学IT");
        request.putQueryParameter("TemplateCode", AliyunSmsTemplateCode.getValue(templateType));
        request.putQueryParameter("TemplateParam", "{\"code\":" + code + "}");

        CommonResponse response = null;
        try {
            response = client.getCommonResponse(request);
        } catch (ClientException e) {
            e.printStackTrace();
        }
        JSONObject result = JSONObject.parseObject(response.getData());
        if (!result.get("Message").equals("OK")) {
            throw new AliyunException(response.getData());
        }
        redisService.addCode(phone,code);
        return code;

    }

    /**
     * 更改用户状态
     *
     * @param userId 需要更改的用户id，由管理员操作
     * @param status
     * @return
     */
    @PutMapping("/changeStatus")
    @ApiAuthorization(auth = AuthConstants.USER_MANAGER_UPDATE)
    public boolean changeUserStatus(@RequestParam("userId") int userId,
                                    @RequestParam(value = "status") @Max(4) @Min(1) Integer status) {
        return userService.changeUserStatus(userId, status);
    }

    /**
     * 批量删除用户
     *
     * @param ids
     * @return
     */
    @DeleteMapping("/deleteUsers")
    @ApiAuthorization(auth = AuthConstants.USER_MANAGER_DELETE)
    public boolean deleteUsersByIds(String ids) {
        return userService.deleteUsersByIds(ids);
    }

    /**
     * 更改用户角色
     *
     * @param userId  需要更改的用户id
     * @param roleIds 角色id的集合
     * @return
     */
    @PutMapping("/changeUserRole")
    @ApiAuthorization(auth = AuthConstants.USER_MANAGER_CHANGE_ROLE)
    public boolean changeUserRole(int userId, String roleIds) {
        return userService.updateUserRole(userId, roleIds);
    }


    /**
     * 用户修改头像，
     *
     * @param headImage
     * @return
     * @throws IOException
     */
    @PostMapping("/updateHeadImage")
    @LoginAuthorization
    public String updateHeadImage(@RequestParam("headImage") MultipartFile headImage) throws IOException {
        int userId = UserContext.getLoginUser().getId();
        List<String> fileUrls = FileUtils.upload(new MultipartFile[]{headImage}, FileContants.USER_IMAGE_PATH);
        String fileUrl = fileUrls.get(0);
        if (fileUrl != null && fileUrl.length() > 0) {
            userService.updateHeadImage(userId, fileUrl);
            return fileUrl;
        }
        return null;

    }

    @GetMapping("/queryUserById")
    @ApiAuthorization(auth = AuthConstants.USER_MANAGER_QUERY)
    public UserVo queryUserById() {
        User user = UserContext.getLoginUser();
        return userService.queryUserById(user.getId());
    }

    /**
     * 需要校验是否登录,
     *
     * @param user
     * @return
     */
    @PutMapping("/updateUserById")
    @LoginAuthorization
    public boolean updateUserById(User user) {
        return userService.updateUserById(user);
    }


    /**
     * 统计用户数量
     * @return
     */
    @GetMapping("/queryUserCount")
    public Integer queryUserCount(){
        return userService.queryUserCount();
    }

}
